<template>
  <div class="sub-category">
    <van-grid :gutter="10" :column-num="3">
      <van-grid-item
        v-for="category in categories"
        :key="category.id"
        :icon="category.imageUrl"
        :text="category.title"
      />
    </van-grid>
  </div>
</template>

<script>
import { getSubCategories } from '@/api/category'
export default {
  name: 'SubCategory',
  data() {
    return {
      categories: [],
    }
  },
  // watch: { // 监听路由变化
  //   $route: {
  //     handler(newVal, oldVal) {
  //       console.log('路由变化了,', newVal.params.cid)
  //       // 根据父级分类id查询子分类
  //       getSubCategories(newVal.params.cid)
  //         .then(data => {
  //           console.log(data)
  //           this.categories = data.categories
  //         })
  //         .catch(err => console.lor('err:', err))
  //     },
  //     deep: true,
  //     immediate: true,
  //   },
  // },
  // created() {
  //   console.log('sub created...')
  // },
  beforeRouteEnter(to, from, next) {
    // console.log('sub before route enter', this)
    next((vm) => {
      // console.log('sub组件实例：', vm)
      // 根据父级分类id查询子分类
      getSubCategories(to.params.cid)
        .then(data => {
          // console.log(data)
          vm.categories = data.categories
        })
        .catch(err => console.log('err:', err))
    })
  },
  beforeRouteUpdate(to, from, next) {
    // console.log('sub before route update')
    // console.log('路由变化了,', newVal.params.cid)
    // 根据父级分类id查询子分类
    getSubCategories(to.params.cid)
      .then(data => {
        // console.log(data)
        this.categories = data.categories
      })
      .catch(err => console.lor('err:', err))
    next()
  },
  beforeRouteLeave(to, from, next) {
    // console.log('sub before route leave')
    next()
  },
}
</script>

<style lang="scss" scoped>

</style>
